package com.xu.cloud.auth.component.oauth;

import com.fasterxml.jackson.core.type.TypeReference;
import com.xu.cloud.auth.enums.ThirdPartyEnum;
import com.xu.cloud.auth.pojo.bo.OAuth2AccessTokenBO;
import com.xu.cloud.auth.pojo.bo.OAuth2UserInfo;
import com.xu.cloud.common.util.JsonUtil;
import com.xu.cloud.common.util.RestTemplateUtil;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * gitee oauth2 授权实现类
 *
 * @author xuguan
 * @since 2025/2/27
 */
@Component
@SuppressWarnings({"SpellCheckingInspection"})
public class GiteeOAuth2Impl extends AbsOAuth2 {

    @Override
    protected ThirdPartyEnum supportThirdPartyEnum() {
        return ThirdPartyEnum.GITEE;
    }

    @Override
    protected String getThirdEmail(String url, OAuth2AccessTokenBO accessTokenBo) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", accessTokenBo.getAccessToken());
        final String result = RestTemplateUtil.doGet(url, params, String.class);
        final List<OAuth2UserInfo> oAuth2UserInfos = JsonUtil.parseGenericType(result, new TypeReference<List<OAuth2UserInfo>>() {
        });
        OAuth2UserInfo oAuth2UserInfo = oAuth2UserInfos.get(0);
        return oAuth2UserInfo.getEmail();
    }

    @Override
    protected String getThirdUserName(String url, OAuth2AccessTokenBO accessTokenBo) {
        Map<String, String> params = new HashMap<>();
        params.put("access_token", accessTokenBo.getAccessToken());
        OAuth2UserInfo oAuth2UserInfo = RestTemplateUtil.doGet(url, params, OAuth2UserInfo.class);
        return oAuth2UserInfo.getName();
    }

}
